package com.example.send.util.tx;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.send.util.kdxf.FileUtil;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.GeneralAccurateOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.GeneralAccurateOCRResponse;
import com.tencentcloudapi.ocr.v20181119.models.GeneralBasicOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.GeneralBasicOCRResponse;
import org.apache.commons.codec.binary.Base64;

import java.io.File;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GeneralAccurateOCR {

    public static String tx1(String path) {
        try{
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new Credential("AKIDPcaHismPlskPs66rPjoeHhrnUyEF2cx3", "tZ1EE1ZtypRowqWx97sOfrqa5LNCm7E8");
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ocr.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            OcrClient client = new OcrClient(cred, "ap-shanghai", clientProfile);
            File f = new File(path);
            byte[] imageByteArray = FileUtil.read(f.getAbsolutePath());
            String imageBase64 = new String(Base64.encodeBase64(imageByteArray), "UTF-8");
            // 实例化一个请求对象,每个接口都会对应一个request对象
            GeneralBasicOCRRequest req = new GeneralBasicOCRRequest();
            req.setImageBase64(imageBase64);
            GeneralBasicOCRResponse resp = client.GeneralBasicOCR(req);
//            GeneralAccurateOCRRequest req = new GeneralAccurateOCRRequest();
//            req.setImageBase64(imageBase64);
//            GeneralAccurateOCRResponse resp = client.GeneralAccurateOCR(req);
            // 输出json格式的字符串回包
            return GeneralAccurateOCRResponse.toJsonString(resp);
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return null;
    }

    public static String tx2(String path) {
        try{
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new Credential("AKIDPcaHismPlskPs66rPjoeHhrnUyEF2cx3", "tZ1EE1ZtypRowqWx97sOfrqa5LNCm7E8");
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ocr.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            OcrClient client = new OcrClient(cred, "ap-shanghai", clientProfile);
            File f = new File(path);
            byte[] imageByteArray = FileUtil.read(f.getAbsolutePath());
            String imageBase64 = new String(Base64.encodeBase64(imageByteArray), "UTF-8");
            GeneralAccurateOCRRequest req = new GeneralAccurateOCRRequest();
            req.setImageBase64(imageBase64);
            GeneralAccurateOCRResponse resp = client.GeneralAccurateOCR(req);
            // 输出json格式的字符串回包
            return GeneralAccurateOCRResponse.toJsonString(resp);
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return null;
    }

    public static void doit(int page) throws InterruptedException {
        String regex = "[\\u4e00-\\u9fa5]+";
        String path = "E:\\back_project\\python\\hanzi\\" +  page + "\\";
        File ffile = new File(path);
        File[] fs = ffile.listFiles();
        Set<String> set = new HashSet<>();
        for (File f : fs) {
//        File f = new File("E:\\back_project\\python\\hanzi\\test\\1.jpg");
            if (!f.isDirectory()) {
                System.out.println(f.getAbsolutePath());
                try {
                    String result = tx1(f.getAbsolutePath());
                    System.out.println(result);
                    if (result == null || result.length() == 0) {
                        result = tx2(f.getAbsolutePath());
                        System.out.println("again:" + result);
                    }
                    JSONObject object = JSONObject.parseObject(result);
                    JSONArray array = object.getJSONArray("TextDetections");
                    String word = "";
                    if (array != null && array.size() > 0) {
                        for (int i = 0; i < array.size(); i++) {
                            JSONObject in = array.getJSONObject(i);
                            String temp = in.getString("DetectedText");
                            Matcher m = Pattern.compile(regex).matcher(temp);
                            if (m.find()) {
                                if (temp.length() > 1) {
                                    temp = temp.substring(0,1);
                                }
                                word = temp;
                                break;
                            }
                        }
                    }
                    if (word != null && word.length() > 0) {
                        System.out.println(word);
                        if (set.contains(word)) {
                            System.out.println("出现重复：" + f.getAbsolutePath() + "-----" + word);
                            continue;
                        } else {
                            set.add(word);
                        }
                        f.renameTo(new File(path + word + ".jpg"));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            Thread.sleep(1000);
        }
    }

    public static void find(String word, int page) throws InterruptedException {
        String path = "E:\\back_project\\jxp\\static\\img\\" +  page + "\\";
        File ffile = new File(path);
        File[] fs = ffile.listFiles();
        for (File f : fs) {
            if (!f.isDirectory()) {
                String name = f.getName().substring(0,1);
//                System.out.println(name + "--" +word);
                if(word.equals(name)) {
                    System.out.println(page);
                }
            }
        }
    }



    public static void main(String[] args) throws InterruptedException {
        for(int i = 1; i<= 50;i++) {
//            find("祆",i);
            find("觳",i);
        }
    }

}
